import axios from "axios";
import vueAxios from "vue-axios";
import { Toast } from 'vant';

export default {
  install (app) {
    app.provide('$http', axios);

    app.use(vueAxios, axios);

    this.init();
  },

  init (router, store, restoreConfig) {

    // this.router = router;
    // this.store = store;
    // this.restoreConfig = restoreConfig;

    // this.restore();

    /**
     * axios请求拦截处理
     */
    axios.interceptors.request.use(config => {
      if (!config.hideTip) {
        let spinText = config.spinText || "正在处理中...";

        Toast.loading({
          overlay: true,
          message: spinText
        })
      }

      // this.restoreOAuth();

      // 在请求头中加入凭证信息
      // config.headers["Authorization"] = store.state.oauth.authorization;
      config.headers["Authorization"] = "token dc\\lujuan1";

      return config;
    });

    /**
     * axios响应拦截处理。
     */
    axios.interceptors.response.use(
      response => {
        if (!response.config.hideTip) {
          // iView.Spin.hide();
        }

        // if (response.data.IsSuccess != undefined && !response.data.IsSuccess) {
        //   if (!response.config.hideTip) {
        //     iView.Notice.error({
        //       title: "错误！",
        //       desc: response.data.ErrorMessage,
        //       duration: 10
        //     });
        //   }
        // }

        return response.data.result ? response.data.result : response.data;
      },
      error => {
        // iView.Spin.hide();

        if (error.response) {
          switch (error.response.status) {
            case 500:
              Toast.fail(`服务器异常:${error.response.data}`);
              break;
            case 504:
              Toast.fail("网络错误");
              break;

            // 401 清除token信息并跳转到登录页面
            case 401:
            case 403:
              Toast.fail({
                message: "您没有权限访问该页面！",
                duration: 5000
              });

              router.push(this.restoreConfig.logOnUrl);

              break;
            default:
              Toast.fail("请求错误！");
          }
        } else {
          Toast.fail("网络错误！");
        }

        return Promise.reject(error);
      }
    );
  },
  restoreOAuth () {
    let oauth = JSON.parse(sessionStorage.getItem('oauth'));

    if (oauth) {
      const self = this;

      if (self.store.getters.isLogged()) {
        self.store.commit('setAccessToken', oauth);
      } else {
        let refreshToken = oauth.refresh_token;

        if (refreshToken) {
          jquery.ajax({
            type: 'get',
            async: false,
            url: `/api/oauth/token/refresh/${refreshToken}`,
            success: function (rs) {
              self.store.commit('setAccessToken', rs);
            }
          });
        }
      }
    }
  },
  restore () {
    if (sessionStorage.getItem('loaded') && sessionStorage.getItem('sid')) {
      const config = this.restoreConfig;

      if (config) {
        let oauth = JSON.parse(sessionStorage.getItem('oauth'));

        if (oauth) {
          this.restoreOAuth();

          const self = this;

          jquery.ajax({
            type: 'get',
            async: false,
            url: `${config.identityUrl}`,
            headers: {
              Authorization: oauth.token_type + ' ' + oauth.access_token
            },
            success: function (res) {
              self.store.commit('logOn', res.Data);
            },
            error: function (xhr, status, error) {
              if (xhr.status == 401) {
                self.router.push(config.logOnUrl);
              }
            }
          });
        }
      }
    } else {
      sessionStorage.setItem('loaded', true);
    }
  }
};